<template>
  <div class="favorites-container">
    <el-card class="header-card">
      <h2><el-icon><Star /></el-icon> 我的收藏</h2>
    </el-card>

    <el-card v-loading="loading">
      <el-empty v-if="favorites.length === 0 && !loading" description="暂无收藏" />

      <el-row :gutter="20" class="favorites-list">
        <el-col :span="6" v-for="favorite in favorites" :key="favorite.favoriteId">
          <transition name="favorite-fade" appear>
            <el-card
              :body-style="{ padding: '0px' }"
              class="favorite-card"
              @click="goToDishDetail(favorite.dish!.dishId!)"
            >
              <div class="dish-image-container">
                <img
                  :src="getImageUrl(favorite.dish?.dishImage || '')"
                  class="dish-image"
                  @error="handleImageError"
                />
                <div class="favorite-overlay">
                  <el-button
                    type="danger"
                    :icon="Delete"
                    circle
                    size="small"
                    @click.stop="handleRemoveFavorite(favorite)"
                  />
                </div>
              </div>
              <div class="dish-info">
                <div class="dish-header">
                  <h3 class="dish-name">{{ favorite.dish?.dishName }}</h3>
                  <el-tag size="small" effect="plain">{{ favorite.dish?.dishType }}</el-tag>
                </div>
                <p class="dish-description">{{ favorite.dish?.dishDescription || '暂无描述' }}</p>
                <div class="dish-footer">
                  <span class="price">¥{{ favorite.dish?.dishPrice }}</span>
                  <el-button
                    type="primary"
                    size="small"
                    :icon="ShoppingCart"
                    :disabled="favorite.dish?.dishStatus === '1'"
                    @click.stop="quickAddToCart(favorite.dish!)"
                  >
                    加入购物车
                  </el-button>
                </div>
              </div>
            </el-card>
          </transition>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Star, Delete, ShoppingCart } from '@element-plus/icons-vue';
import { getUserFavorites, deleteFavorite } from '@/api/favorite';
import { getDishById } from '@/api/dish';
import { useCartStore } from '@/stores/cart';
import { useUserStore } from '@/stores/user';
import type { Favorite, Dish } from '@/types';
import { ElMessage, ElMessageBox } from 'element-plus';

const router = useRouter();
const cartStore = useCartStore();
const userStore = useUserStore();

const favorites = ref<Favorite[]>([]);
const loading = ref(false);

// 加载收藏列表
const loadFavorites = async () => {
  if (!userStore.userId) return;
  
  loading.value = true;
  try {
    const response = await getUserFavorites(userStore.userId);
    if (response.operateResult === 'SUCC' && response.data) {
      // 加载每个收藏项的菜品信息
      const favoritesWithDishes = await Promise.all(
        response.data.map(async (favorite) => {
          const dishRes = await getDishById(favorite.dishId);
          if (dishRes.operateResult === 'SUCC' && dishRes.data) {
            return { ...favorite, dish: dishRes.data };
          }
          return favorite;
        })
      );
      favorites.value = favoritesWithDishes;
    } else {
      favorites.value = [];
    }
  } catch (error) {
    ElMessage.error('加载收藏失败');
    favorites.value = [];
  } finally {
    loading.value = false;
  }
};

// 跳转到菜品详情
const goToDishDetail = (dishId: number) => {
  router.push(`/user/dish/${dishId}`);
};

// 取消收藏
const handleRemoveFavorite = (favorite: Favorite) => {
  ElMessageBox.confirm('确定要取消收藏吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteFavorite(favorite.favoriteId!);
      if (response.operateResult === 'SUCC') {
        ElMessage.success('已取消收藏');
        await loadFavorites();
      } else {
        ElMessage.error(response.errorMsg || '操作失败');
      }
    } catch (error: any) {
      ElMessage.error(error.message || '操作失败');
    }
  }).catch(() => {});
};

// 快速加入购物车
const quickAddToCart = async (dish: Dish) => {
  if (!userStore.userId) {
    ElMessage.warning('请先登录');
    return;
  }
  
  if (dish.dishStatus === '1') {
    ElMessage.warning('该菜品已停售');
    return;
  }
  
  await cartStore.addItem(userStore.userId, dish.dishId!, 1);
};

// 获取图片URL
const getImageUrl = (imagePath: string) => {
  if (!imagePath || !imagePath.trim()) {
    return 'https://via.placeholder.com/300x200?text=No+Image';
  }
  if (imagePath.startsWith('http')) {
    return imagePath;
  }
  return `http://localhost:8060${imagePath}`;
};

// 图片加载错误处理
const handleImageError = (e: Event) => {
  const target = e.target as HTMLImageElement;
  target.src = 'https://via.placeholder.com/300x200?text=No+Image';
};

onMounted(() => {
  loadFavorites();
});
</script>

<style scoped>
.favorites-container {
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.header-card {
  margin-bottom: 20px;
}

.header-card h2 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 10px;
  color: #303133;
}

.favorites-list {
  margin-top: 20px;
}

.favorite-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  overflow: hidden;
}

.favorite-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);
}

.favorite-fade-enter-active {
  animation: favoriteFadeIn 0.5s ease-out;
}

@keyframes favoriteFadeIn {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.dish-image-container {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.dish-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.favorite-card:hover .dish-image {
  transform: scale(1.1);
}

.favorite-overlay {
  position: absolute;
  top: 10px;
  right: 10px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.favorite-card:hover .favorite-overlay {
  opacity: 1;
}

.dish-info {
  padding: 15px;
}

.dish-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.dish-name {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
  margin-right: 10px;
}

.dish-description {
  color: #909399;
  font-size: 14px;
  margin: 10px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  min-height: 40px;
}

.dish-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

.price {
  font-size: 20px;
  font-weight: bold;
  color: #f56c6c;
}
</style>
